﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ShoppingApp2.Common.Models;
using System.Data.SqlClient;
using System.Data;

namespace ShoppingApp2.Common
{
    public class Transaction : TransactionModel
    {
        public Transaction(string connectionString)
        {
            this.connectionString = connectionString;

            // Connection object
            this.connection = new SqlConnection(connectionString);
        }

        /// <summary>
        /// Begins transaction
        /// </summary>
        public void BeginTransaction()
        {
            if (this.connection.State == ConnectionState.Closed || this.connection.State == ConnectionState.Broken)
                this.connection.Open();

            transaction = connection.BeginTransaction();
        }

        /// <summary>
        /// Commits opened transaction
        /// </summary>
        public void Commit()
        {
            if (transaction != null && transaction.Connection != null)
            {
                transaction.Commit();
                EndTransaction();
            }
        }

        /// <summary>
        /// Rollbacks opened transaction
        /// </summary>
        public void RollBack()
        {
            if (transaction != null && transaction.Connection != null)
            {
                transaction.Rollback();
                EndTransaction();
            }
        }
        
        /// <summary>
        /// Ends transaction by closing connection
        /// </summary>
        private void EndTransaction()
        {
            if (this.connection.State == ConnectionState.Open || this.connection.State == ConnectionState.Broken)
                this.connection.Close();
        }

        public SqlConnection Connection 
        {
            get { return this.connection; }    
        }

        public SqlTransaction TransactionSql
        {
            get { return this.transaction; }
        }
    
    }
}